package com.lwj.liwanjia.view.activity.personal.qian_bao;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lwj.liwanjia.R;
import com.lwj.liwanjia.base.BaseActivity;
import com.lwj.liwanjia.bean.AllMoneyBean;
import com.lwj.liwanjia.bean.CenterBean08;
import com.lwj.liwanjia.bean.PwdBean;
import com.lwj.liwanjia.config.URLConstant;
import com.lwj.liwanjia.impl.AllMoneyView;
import com.lwj.liwanjia.impl.IsSetPwdView;
import com.lwj.liwanjia.presenter.AllMoeyPresenter;
import com.lwj.liwanjia.presenter.IsSetPwdPresenter;
import com.lwj.liwanjia.utils.PwdDialog;
import com.lwj.liwanjia.utils.SpUtils;
import com.lwj.liwanjia.utils.SpfUtils;
import com.lwj.liwanjia.utils.ZfPwdDialog;
import com.lwj.liwanjia.view.activity.indent.PayCompleteActivity;
import com.lwj.liwanjia.view.activity.login.LoginActivity;

import java.io.IOException;

import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by 001 on 2017/9/21.
 */

public class ZhuanZhangTwoActivity extends BaseActivity implements View.OnClickListener, IsSetPwdView, AllMoneyView {

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case 0:
                    Toast.makeText(ZhuanZhangTwoActivity.this, "数据有误", Toast.LENGTH_LONG).show();
                    pwdDialog.dismiss();
                    break;
                case 1:
                    Toast.makeText(ZhuanZhangTwoActivity.this, "转账成功", Toast.LENGTH_LONG).show();
                    pwdDialog.dismiss();
                    finish();
                    break;
                case 3:
                    TextView[] tvList = pwdDialog.getTvList();
                    for (TextView tv : tvList) {
                        tv.setText("");
                    }
                    pwdDialog.getTvError().setVisibility(View.VISIBLE);
                    break;
                case 11:
                    Toast.makeText(ZhuanZhangTwoActivity.this, "余额不足", Toast.LENGTH_SHORT).show();
                    pwdDialog.dismiss();
                    break;
            }
        }
    };


    private TextView tv_back;
    private TextView tv_title;
    private Button bt_sure;//确认转账
    private EditText et_money;//金额
    private EditText et_beiZhu;//备注
    private CircleImageView circle_photo;//头像
    private TextView tv_zhangHao;//账号
    private TextView tv_name;//名字
    private String otherNumber;//对方账号
    private PwdDialog pwdDialog;
    private String token;
    private IsSetPwdPresenter isSetPwdPresenter;
    private String money;
    private String beiZhu;
    private TextView tvBuzu;//余额不足
    private double balance;
    private TextView tvAllmoney;
    private AllMoeyPresenter moneyPresnter;

    @Override
    protected void initView() {

        tv_back = (TextView) findViewById(R.id.tv_left);
        tv_title = (TextView) findViewById(R.id.tv_title);
        bt_sure = (Button) findViewById(R.id.bt_sure);
        circle_photo = (CircleImageView) findViewById(R.id.circle_photo);
        tv_zhangHao = (TextView) findViewById(R.id.tv_zhangHao);
        et_money = (EditText) findViewById(R.id.et_money);
        et_beiZhu = (EditText) findViewById(R.id.et_beiZhu);
        tv_name = (TextView) findViewById(R.id.tv_name);
        tvBuzu = (TextView) findViewById(R.id.tv_buzu);
        tvAllmoney= (TextView) findViewById(R.id.tv_allmoney);

        tv_back.setVisibility(View.VISIBLE);
        tv_title.setVisibility(View.VISIBLE);
        tv_title.setText("转账");

        tv_back.setOnClickListener(this);
        bt_sure.setOnClickListener(this);

        isSetPwdPresenter = new IsSetPwdPresenter(this);
        token = SpfUtils.getSpfUtils(this).getToken();
        moneyPresnter = new AllMoeyPresenter(this);
        listener();
    }

    private void listener() {
        et_money.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s.toString())) {
                    double zMoney = Double.parseDouble(s.toString());
                    if (zMoney > balance) {
                        tvBuzu.setVisibility(View.VISIBLE);
                    } else {
                        tvBuzu.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    protected void initData() {

        Intent intent = getIntent();
        String photoUrl = intent.getStringExtra("photoUrl");
        String name = intent.getStringExtra("name");
        String zhangHao = intent.getStringExtra("zhangHao");
        otherNumber = intent.getStringExtra("number");

        if (!TextUtils.isEmpty(photoUrl)) {
            Glide.with(this).load(photoUrl).error(R.mipmap.touxiang).into(circle_photo);
        }

        if (!TextUtils.isEmpty(name)) {
            tv_name.setText(name);
        }

        if (!TextUtils.isEmpty(zhangHao)) {
            tv_zhangHao.setText(zhangHao);
        }
        moneyPresnter.getAllMoey(token);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_zhuan_zhang_two;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //返回
            case R.id.tv_left:
                finish();
                break;
            //确认转账
            case R.id.bt_sure:
                money = et_money.getText().toString().trim();
                beiZhu = et_beiZhu.getText().toString().trim();
                if (!TextUtils.isEmpty(money)) {
                    double m = Double.parseDouble(money);
                    if (m > balance) {
                        Toast.makeText(this, "金额已超过可转金额", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    isSetPwdPresenter.isSetPwd(token);

                } else {
                    Toast.makeText(ZhuanZhangTwoActivity.this, "金额或备注不能为空", Toast.LENGTH_LONG).show();
                }

                break;
        }
    }

    //连网,获取数据
    private void initOkHttp01(String money, String beiZhu, String password) {

        String url = URLConstant.BASE_URL + "oneCard/transfer";
        String token = SpfUtils.getSpfUtils(this).getToken();

        OkHttpClient mOkHttpClient = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("token", token)
                .add("toName", otherNumber)
                .add("money", money)
                .add("content", beiZhu)
                .add("password", password)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();
        Call mCall = mOkHttpClient.newCall(request);
        mCall.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //Log.d("Tag", "分类数据获取失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //Log.d("Tag", "分类图数据获取成功");

                String result = null;

                try {
                    result = response.body().string();
                    //Log.d("Tag",result);
                    parse01(result);
                } catch (Exception e) {

                }

            }
        });
    }

    //解析
    private void parse01(String result) {

        Gson gson = new Gson();
        CenterBean08 bean = gson.fromJson(result, CenterBean08.class);

        if (bean != null) {

            switch (bean.getState()) {

                case 0:
                    mHandler.sendEmptyMessage(0);
                    break;
                case 1://成功
                    mHandler.sendEmptyMessage(1);
                    break;
                case 3://密码错误
                    mHandler.sendEmptyMessage(3);
                    break;
                case 11://余额不足
                    mHandler.sendEmptyMessage(11);
                    break;
            }
        }
    }

    @Override
    public void showError(Exception e) {
        Toast.makeText(this, "访问网络失败", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void getAllMoney(AllMoneyBean allMoneyBean) {
        if (allMoneyBean.getState() == 0) {
            Toast.makeText(this, "数据加载失败", Toast.LENGTH_SHORT).show();
        } else if (allMoneyBean.getState() == 1) {
            balance = allMoneyBean.getData().getBalance();
            tvAllmoney.setText("账户余额:¥"+balance);
        }
    }

    @Override
    public void isSetPwd(PwdBean pwdBean) {
        if (pwdBean.getState() == 0) {
            startActivity(new Intent(this, LoginActivity.class));
            finish();
        } else if (pwdBean.getState() == 1) {
            if (pwdBean.isData()) {//设置过支付密码
                pwdDialog = new PwdDialog(this);
                pwdDialog.show();
                pwdDialog.setOnFinishInput(new PwdDialog.OnPasswordInputFinish() {
                    @Override
                    public void inputFinish() {
                        initOkHttp01(money, beiZhu, pwdDialog.getStrPassword());
                    }
                });
            } else {
                ZfPwdDialog zfPwdDialog = new ZfPwdDialog(this);
                zfPwdDialog.show();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (moneyPresnter != null) {
            moneyPresnter = null;
        }
        if (isSetPwdPresenter != null) {
            isSetPwdPresenter = null;
        }
    }
}
